<template>
  <!-- 短信分享链接 -->
  <div class="wrap">
    <div v-if="noShow">
      <!-- 邀请人信息 -->
      <div class="invitees-information">
        <div class="head-portrait">
          <img :src="active" alt />
        </div>
        <div class="information">
          <div class="name">{{ names }}</div>
          <div class="companyName">{{ companyName }}</div>
        </div>
      </div>
      <!-- 邀请加入或者已经加入 -->
      <div class="join">邀请你加入“{{ companyName }}”</div>
      <!-- 验证邀请是否过期 -->
      <div class="isShow" v-if="!alreadyJoin">
        <!-- 失效 -->
        <div v-if="!urlValid" class="LinkFailure">该链接失效</div>
        <!-- 可加入 -->
        <div v-else>
          <!-- 手机号 -->
          <el-form
            :model="codeForm"
            :rules="codeRules"
            ref="codeForm"
            @submit.native.prevent
            label-position="top"
          >
            <el-form-item prop="phone" :error="tips">
              <el-input
                placeholder="请输入手机号"
                @input="realTime($event)"
                v-model="codeForm.phone"
                maxlength="11"
                class="phone"
              >
                <template slot="prefix">
                  <span class="country-code">+ 86</span>
                  <div class="vertical-bar"></div>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="code" :error="codeTips">
              <el-input
                v-model="codeForm.code"
                maxlength="4"
                placeholder="输入验证码"
                oninput="value=value.replace(/[^\d]/g,'')"
                :disabled="codeInput"
              >
                <template slot="suffix">
                  <el-button
                    v-if="codeForm.phone !== '' && !timer && codeHighl"
                    style="color: #02aac2 !important; font-size: 16px; padding-right: 10px;"
                    type="text"
                    @click="getVerificationCode()"
                  >{{ verificationText }}</el-button>
                  <el-button
                    v-else
                    disabled
                    type="text"
                    :style="{
                      color: '#02AAC2 !important',
                      fontSize: '16px',
                      paddingRight: '10px'
                    }"
                  >
                    {{
                      isNaN(parseInt(disableverificationText))
                        ? disableverificationText
                        : parseInt(disableverificationText) + 's'
                    }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="真实姓名" prop="name">
              <el-input v-model="codeForm.name" placeholder="请输入真实姓名" maxlength="10"></el-input>
            </el-form-item>
            <el-form-item label="部门">
              <el-input v-model="codeForm.deptName" placeholder="请输入要加入的部门名称" maxlength="12"></el-input>
            </el-form-item>
            <el-form-item label="岗位">
              <el-input v-model="codeForm.postName" placeholder="请输入岗位名称" maxlength="12"></el-input>
            </el-form-item>
            <el-form-item label="申请理由">
              <el-input type="textarea" v-model="codeForm.reason" placeholder="请输入加入公司的理由"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <!-- 加入公司成功 -->
    <div v-else class="join-successfully">
      <div>
        <img :src="logo" alt />
      </div>
      <div v-if="isRepeatSubmission">
        <div>已提交加入申请{{ companyName }}</div>
        <div>请前往查看吧!</div>
      </div>
      <div v-if="!isRepeatSubmission">
        <div>你已加入“{{ companyName }}”</div>
        <div>请勿重复申请!</div>
      </div>
    </div>
    <!-- 下载或加入 -->
    <div class="jions">
      <!-- 下载 -->
      <div v-if="isShow || urlValid === false">
        <van-button type="info" @click="openApp">下载</van-button>
      </div>
      <!--  -->
      <div v-else>
        <van-button type="info" @click="jion('codeForm')">申请加入</van-button>
      </div>
    </div>
    <!-- 跳转天使搜 -->
    <div class="jumpBottom" v-if="isShow || alreadyJoin">
      <div class="jump" @click="openApp">
        已有天使搜，前往打开
        <van-icon name="arrow" />
      </div>
    </div>
    <div></div>
  </div>
</template>

<script>
import {
  getJoinCompanyInviteInfo,
  sendCode,
  checkCodeInvalid,
  userJoinCompany
} from "../../api/logo.js";
export default {
  name: "shareLinks",
  data () {
    const validaPhone = (rule, value, callback) => {
      const that = this
    if (!value) {
      that.codeHighl = true
      that.codeInput = true
      return  callback(new Error('请输入手机号'))
      } else if (!/^1\d{10}$/.test(value)) {
       that.codeHighl = false
       return callback(new Error('手机号格式错误'))
      } else {
        that.codeHighl = true
        that.codeInput = false
       return callback()
      }
    }
    const validaCode = (rule, value, callback) => {
      if (!value) {
       return callback(new Error('输入验证码'))
      } else if (!value && value.length !== 4) {
       return callback(new Error('验证码错误，请重新输入'))
      } else {
       return callback()
      }
    }
    return {
      companyId: '',
      names: "",
      userId: '',
      companyName: "",
      isShow: false, //
      noShow: true,
      // 是否已经加入天使搜
      alreadyJoin: false,
      error: false,
      active: "",
      urlValid: true,
      tips: null,
      logo: require("@/assets/logos.png"), // logo图
      verificationText: '获取验证码', // 获取验证码or重新获取验证码
      disableverificationText: '获取验证码', // 获取验证码or倒计时
      timer: null, // 倒计时
      codeHighl: false, // 验证码高亮
      igToken: "",
      codeForm: {
        phone: '', // 手机号码
        code: '', // 验证码
        name: '',
        deptName: '',
        postName: '',
        reason: ''
      },
      codeTips: null, // 验证码错误提示
      codeRules: {
        phone: [{ required: true, validator: validaPhone, trigger: 'blur' }],
        code: [{ required: true, validator: validaCode, trigger: 'blur' }],
        name: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }]
      },
      isRepeatSubmission: true,
      codeInput: true
    };
  },
  created () {
    var url = window.location.href.split("?")[1].split("&");
    var Id = url[0].split("=")[1];
    let urls1 = Id.split("#/")[0];
    this.igToken = urls1;
    // this.igToken = "78f930c6-1e7e-4099-8e69-d28ff1c45727"
    this.invitees();
  },
  methods: {
    // input框光标选中的时候，清除form校验
    // inputFocus (prop) {
    //   this.$refs.codeForm.clearValidate([prop])
    // },
    // 如果本地安装了app，直接打开
    openApp () {
      if (/(Android)/i.test(navigator.userAgent)) {
        window.location.href = "fenmu://tianshisou:10080/splash";
        window.setTimeout(function () {
          window.location.href = "http://www.wjtr.com/download/index.html";
        }, 3000);
      } else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        window.location.href =
          "https://apps.apple.com/cn/app/id1516734852"; /***打开app的协议，有IOS同事提供***/
      }
    },
    realTime (event) {
      event = event.replace(/[^\d]/g, '')
      this.codeForm.phone = event
      if (this.codeForm.phone.length >= 11) {
        this.$refs.codeForm.validateField('phone')
      }
    },
    // 点击获取验证码
    getVerificationCode () {
      // 校验手机号
      let flag = true
      this.$refs.codeForm.validateField('phone', (valid) => {
        flag = valid
      })
      if (flag !== '') return
      this.tips = ''
      this.verifcationCode();
    },
    // 获取邀请人的信息
    invitees () {
      const params = {
        igToken: this.igToken
      };
      getJoinCompanyInviteInfo(params).then(res => {
        console.log(res.data, 2313213)
        this.names = res.data.createUserNickName
        this.companyName = res.data.companyName
        this.active = res.data.createUserAvatar
        this.urlValid = res.data.urlValid
        this.companyId = res.data.companyId
        this.phone = res.data.receiverPhone.replace(
          /^(.{3})(.*)(.{4})$/,
          "$1 $2 $3"
        );
        this.receiverPhone = res.data.receiverPhone;
      });
    },
    // 发送验证码
    verifcationCode () {
      const params = {
        phone: this.codeForm.phone,
        codeType: 2
      };
      sendCode(params).then(res => {
        if (res.code === "1") {
          this.tips = res.msg;
          this.error = true;
        } else if (res.code === "0000") {
          this.tips = null
          this.error = false;
          const TIME_COUNT = 60
          if (!this.timer) {
            this.disableverificationText = TIME_COUNT
            this.timer = setInterval(() => {
              if (
                this.disableverificationText > 0 &&
                this.disableverificationText <= TIME_COUNT
              ) {
                this.disableverificationText--
              } else {
                clearInterval(this.timer)
                this.verificationText = '重新获取验证码'
                this.disableverificationText = '重新获取验证码'
                this.timer = null
              }
            }, 1000)
          }
        }
      });
    },
    // 校验验证码
    loseFocus () {
      if(this.codeForm.code){
         this.codeTips = null
      const params = {
        phone: this.codeForm.phone,
        codeType: 2,
        code: this.codeForm.code
      };
      checkCodeInvalid(params).then(res => {
        console.log(res, 999999)
        if (res.code === "1") {
          this.codeTips = res.msg
          this.error = true
        } else if (res.data.errorCode === "1") {
          this.codeTips = res.data.errorMsg
          this.error = true
        } else {
          this.codeTips = null
          this.error = false
          if(res.data.userInfo){
            this.userId = res.data.userInfo.userId
            this.checkIn()
          }
        }
      })
      } else {
         this.codeTips = '验证码不能为空'
      }
    },
    // 校验成功之后加入公司
    checkIn () {
      const params = {
        companyId: this.companyId,
        userId: this.userId,
        deptName: this.codeForm.deptName,
        userName: this.codeForm.name,
        postName: this.codeForm.postName,
        reason: this.codeForm.reason
      };
      userJoinCompany(params).then(res => {
        if (res.code === "0000") {
          this.isShow = true;
          this.noShow = false;
          this.isRepeatSubmission = true
        } else {
          this.isShow = true;
          this.noShow = false;
          this.isRepeatSubmission = false
        }
      });
    },
    //加入公司回调
    jion (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loseFocus()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.wrap {
  max-width: 375px;
  margin: 0 auto;
  user-select: none;
  margin-top: 43px;
  padding: 0 16px;
}

.invitees-information {
  display: flex;
}

.head-portrait img {
  width: 48px;
  height: 48px;
  border-radius: 3px;
}

.information {
  display: flex;
  flex-direction: column;
  margin-left: 12px;
}

.name {
  font-size: 17px;
  font-family: PingFang-SC-Medium, PingFang-SC;
  font-weight: 500;
  margin-bottom: 6px;
  margin-right: 40px;
  color: #03111b;
}

.companyName {
  font-size: 14px;
  font-family: PingFang-SC-Medium, PingFang-SC;
  font-weight: 500;
  color: #9ca1a5;
}

.join {
  text-align: center;
  margin-top: 47px;
  font-size: 22px;
  font-family: PingFang-SC-Bold, PingFang-SC;
  font-weight: bold;
  color: #03111b;
  line-height: 30px;
}

.LinkFailure {
  text-align: center;
  font-size: 17px;
  font-family: PingFang-SC-Medium, PingFang-SC;
  font-weight: 500;
  color: #f94b4b;
  line-height: 24px;
  margin: 76px 0px;
}
/deep/.van-button--info {
  width: 343px;
  height: 48px;
  background: #02aac2;
  border-radius: 4px;
  color: #fff;
  border: none;
}
.jumpBottom {
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
  bottom: 21px;
}
.jump {
  text-align: center;
  font-size: 14px;
  font-family: PingFang-SC-Medium, PingFang-SC;
  font-weight: 500;
  color: #2e7ff7;
  line-height: 20px;
}
/deep/ .van-icon-arrow {
  vertical-align: -3px;
}
/deep/ .el-form-item__label {
  font-size: 14px;
  font-family: PingFang-SC-Medium, PingFang-SC;
  font-weight: 500;
  color: #03111b;
  line-height: 14px;
}
/deep/ .el-textarea__inner {
  width: 100%;
  height: 120px;
  background: #f8fafc;
  border-radius: 4px;
  resize: none;
}
#yzm {
  padding: 0px 16px;
  height: 100%;
  width: 345px;
  box-sizing: border-box;
  background-color: #f8fafc;
  border: none;
  -webkit-appearance: none;
  font-size: 17px;
  font-family: PingFang-SC-Medium, PingFang-SC;
  font-weight: 500;
}

.jions {
  margin-top: 16px;
  text-align: center;
  margin-bottom: 16px;
}
.isShow {
  margin-top: 55px;
}
input {
  outline-color: #3b81ea;
}
.join-successfully div:nth-child(2) {
  font-size: 22px;
  font-family: PingFang-SC-Bold, PingFang-SC;
  font-weight: bold;
  color: #03111b;
  margin-top: 29px;
  line-height: 30px;
}
.join-successfully div:nth-child(3) {
  font-size: 17px;
  font-family: PingFang-SC-Medium, PingFang-SC;
  font-weight: 500;
  color: #03111b;
  line-height: 21px;
  margin-top: 12px;
}
.join-successfully div:nth-child(1) {
  img {
    width: 70px;
    height: 70px;
  }
}
.join-successfully {
  text-align: center;
  margin-top: 98px;
}
/deep/ .el-input__inner {
  border: none;
  background: #f8fafc;
}
.country-code {
  padding-left: 9px;
  color: #1b292b;
  font-weight: bold;
}
.vertical-bar {
  display: inline-block;
  width: 1px;
  height: 16px;
  background: #666666;
  vertical-align: middle;
  margin: 0 12px;
}
.phone {
  /deep/ .el-input__inner {
    padding-left: 80px;
  }
}
</style>
